package com.example.mosbytest.ui.presenter;


import android.support.annotation.NonNull;

import com.example.mosbytest.api.Listener;
import com.example.mosbytest.api.LoginApi;
import com.example.mosbytest.ui.view.LoginView;
import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter;

/**
 * @author lizhangqu
 * @since 2016-02-21 10:31
 */
public class LoginPresenter extends MvpBasePresenter<LoginView> {

    public void login(final String username, final String password) {

        ifViewAttached(new ViewAction<LoginView>() {
            @Override
            public void run(@NonNull LoginView view) {
                if (username == null || username.equals("")) {
                    if (view != null) {
                        view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_EMPTY);
                        return;
                    }
                } else if (password == null || password.equals("")) {
                    if (view != null) {
                        view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_EMPTY);
                        return;
                    }
                }
            }
        });

        Listener<String> listener = new Listener<String>() {
            @Override
            public void onSuccess(String str) {
                ifViewAttached(new ViewAction<LoginView>() {
                    @Override
                    public void run(@NonNull LoginView view) {
                        if (view != null) {
                            view.onLoginSuccess();
                        }
                    }
                });

            }

            @Override
            public void onFailure(final int code) {

                ifViewAttached(new ViewAction<LoginView>() {
                    @Override
                    public void run(@NonNull LoginView view) {
                        if (code == LoginView.USERNAME_OR_PASSWORD_ERROR) {
                            if (view != null) {
                                view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_ERROR);
                            }
                        } else {
                            if (view != null) {
                                view.onLoginFailure(LoginView.SERVER_ERROR);
                            }
                        }
                    }
                });
            }
        };

        LoginApi.login(username, password, listener);
    }
}
